from odoo import api, fields, models, _
import logging
from odoo.exceptions import UserError

logger = logging.getLogger(__name__)


class VaccineInformationEntering(models.Model):
    _name = "vaccine.information.entering"
    _description = "vaccine information entering"

    # 疫苗ID
    vaccine_id = fields.Char('疫苗ID', required=True)

    @api.model
    def create(self, vals):
        vals['vaccine_id'] = self.env['ir.sequence'].next_by_code('vaccine.information.entering') or ''
        return super(VaccineInformationEntering, self).create(vals)

    # 疫苗名称

    name = fields.Char(
        string='疫苗中文名',
        required=True
    )
    name_en = fields.Char(
        string='疫苗英文名'
    )
    name_usual = fields.Char(
        string='疫苗通用中文名',
        required=True
    )
    name_usual_en = fields.Char(
        string='疫苗通用英文名'
    )
    # 疫苗类别
    vaccine_category = fields.Selection(
        [
            ('1', 'HPV疫苗'),
            ('2', '卡介苗'),
            ('3', '小儿麻痹疫苗'),
            ('4', '狂犬疫苗'),
            ('5', '乙肝疫苗'),
            ('6', '水痘疫苗'),
            ('7', '其他'),
        ],
        string='疫苗类别',
        required=True
    )

    # 疫苗属性
    vaccine_attribute = fields.Selection(
        [
            ('1', '第一类疫苗'),
            ('2', '第二类疫苗')
        ],
        string='疫苗属性',
        required=True
    )

    # 单位名称
    organization_name = fields.Char('单位名称', required=True)

    # 日期
    date = fields.Date('日期', required=True)

    # 生产企业
    manufacturer = fields.Many2one('factory', string='生产企业', required=True)

    # 生产批号
    batch_number = fields.Char('生产批号', required=True)

    # 批准文号
    allow_number = fields.Char('批准文号', required=True)

    # 有效期
    period_validity = fields.Char('有效期(天)', required=True)

    # 单据类型（勾选）
    document_type = fields.Selection(
        [
            ('1', '出库'),
            ('2', '未出库'),
        ],
        string='单据类型',
        required=True
    )

    # 剂型
    vaccine_form = fields.Selection(
        [
            ('1', '液体安剖瓶'),
            ('2', '冻干西林瓶'),
            ('3', '其他'),
        ],
        string='剂型',
        required=True
    )

    # 规格
    standard = fields.Selection(
        [
            ('1', '0.5ml/支'),
            ('2', '1.0ml/支'),
            ('3', '1.5ml/支'),
            ('4', '2.0ml/支'),
            ('5', '2.5ml/支'),
            ('6', '其他'),
        ],
        string='规格',
        required=True
    )

    # 入库量
    receipt = fields.Char('入库量', required=True)

    # 出库量
    outbound_quantity = fields.Char('出库量', required=True)

    # 接种人数
    vaccine_number = fields.Char('接种人数', required=True)

    # 本批结余
    surplus = fields.Char('本批结余', required=True)

    # 结余量
    surplus_number = fields.Char('结余量', required=True)

    # 经手人
    reponsible_number = fields.Many2one(
        'res.users',
        string='经手人',
        required=True
    )
    is_bad = fields.Boolean(
        '是否为问题疫苗',
        default=False
    )

    def define_bad_vaccine(self):
        self.ensure_one()
        # 检验此数据集中是否包含单条数据，否则报错
        sql_query = """SELECT name FROM get_vaccine where vaccine_id = '{vaccine_id}' and is_bad = true""".format(
            vaccine_id=self.vaccine_id)
        self.env.cr.execute(sql_query)
        result = self.env.cr.dictfetchall()
        # 通过原生sql检验当前疫苗的id是否在问题疫苗表中有对应的数据
        if result:
            raise UserError(_('疫苗%s已被标记!') % self.name)
        # 有则报错
        else:
            # logger.info("Here is the name: %s", result)
            check_as_superuser = self.env['get.vaccine'].sudo()
            # sudo():使用现有数据集创建一个新运行环境，得到一个基于新运行环境的数据集的拷贝
            check_as_superuser.create({
                'vaccine_id': self.vaccine_id,
                'name': self.name,
                'name_en': self.name_en,
                'vaccine_category': self.vaccine_category,
                'vaccine_attribute': self.vaccine_attribute,
                'organization_name': self.organization_name,
                'date': self.date,
                'manufacturer': self.manufacturer.id,
                'batch_number': self.batch_number,
                'allow_number': self.allow_number,
                'period_validity': self.period_validity,
                'document_type': self.document_type,
                'vaccine_form': self.vaccine_form,
                'standard': self.standard,
                'receipt': self.receipt,
                'outbound_quantity': self.outbound_quantity,
                'vaccine_number': self.vaccine_number,
                'surplus': self.surplus,
                'surplus_number': self.surplus_number,
                'reponsible_number': self.reponsible_number.id,
                'is_bad': True,
            })
            # 创造新的一条数据
            self.is_bad = True

            return {
                'type': 'ir.actions.act_window',
                'view_type': 'kanban',
                'view_mode': 'kanban,tree,form',
                'res_model': 'get.vaccine',
                'target': 'new',
            }
            # 此处return作为悬浮式页面跳转
